package cyce.dfs.fileChooser;

import java.io.StringReader;
import java.util.*;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.*;

import org.jdom.*;
import org.jdom.input.*;

public class FileModel {
	
	private Directory root;
	private FileTreeModel treeModel;
	
	public FileModel(String filesXML) {
		this.root = new Directory(null, "root");
		this.treeModel = new FileTreeModel();
		this.loadXML(filesXML);
	}
	
	private void loadXML(String filesXML) {
		Element rootElement;
		try {
			SAXBuilder builder = new SAXBuilder();
			Document doc = builder.build(new StringReader(filesXML));
			rootElement = doc.getRootElement();
		}
		catch (Exception e) {
			e.printStackTrace();
			return;
		}
		
		this.loadChildren(this.root, rootElement.getChildren());
	}
	
	private void loadChildren(Directory directory, List children) {
		for (int i = 0; i < children.size(); i++) {
			Element element = (Element)children.get(i);
			String name = element.getAttributeValue("name");
			if (element.getName() == "directory") {
				Directory newDir = directory.addDirectory(name);
				this.loadChildren(newDir, element.getChildren());
			}
			else if (element.getName() == "file") {
				File newFile = directory.addFile(name);
			}
		}
	}
	
	public FileTreeModel getTreeModel() {
		return this.treeModel;
	}
	
	public class FileTreeModel implements TreeModel {
		private ArrayList<TreeModelListener> listeners;
		
		public FileTreeModel() {
			this.listeners = new ArrayList<TreeModelListener>();
		}
		
		public void addTreeModelListener(TreeModelListener listener) {
			this.listeners.add(listener);
		}

		public Object getChild(Object file, int index) {
			return ((File)file).getChildAt(index);
		}

		public int getChildCount(Object file) {
			return ((File)file).getChildCount();
		}

		public int getIndexOfChild(Object directory, Object file) {
			return ((File)directory).getIndex((File)file);
		}

		public Object getRoot() {
			return FileModel.this.root;
		}

		public boolean isLeaf(Object file) {
			return ((File)file).isLeaf();
		}

		public void removeTreeModelListener(TreeModelListener listener) {
			this.listeners.remove(listener);
		}

		public void valueForPathChanged(TreePath path, Object file) {
			// this method should never be called - the user cannot change stuff in the tree
			assert false;
		}
	}
}
